#include "keyboard.h"

#include <stdbool.h>
#include "delay.h"

static uint8_t KBD_Pressed = 0;
//键盘当前状态
//0 = Released
//1 = Pressed
//2 = Need debounce

//等待一个按键
int8_t KBD_WaitKey(uint16_t time) {
	uint16_t delaytime = 0;
	if (KBD_Pressed == 2) {
		delaytime = KBD_DEBOUNCE_TIME + 1;
		KBD_Pressed = 1;
	}
	delay(delaytime, false);
	while (time > 0) {
		uint8_t buffer;
		bool pressed;
		buffer = KBD_Port;
		pressed = buffer != 0xFF;
		if (pressed ^ KBD_Pressed) {
			if (pressed) {
				//just pressed
				KBD_Pressed = 2;
			} else {
				//just released
				KBD_Pressed = 0;
			}
		}
		delay(1, true);
		time--;
	}
	return -1; //timeout
}
